<?php
/**
 * Created by PhpStorm.
 * User: wangan
 * Date: 2016/12/5
 * Time: 14:43
 */

namespace App\Http\Service;
use App\Models\User as AdminUser;
use Illuminate\Support\Facades\DB;
class AdminUserService
{
    const INIT_PASSWD='123456';
    public static function getUserListPageInit($pageSize=DEFAULT_PAGESIZE,$searchVal=null){

        if(!empty($searchVal)){
            return AdminUser::where('name','like','%'.$searchVal.'%')
                ->paginate($pageSize);
        }
        return AdminUser::paginate($pageSize);

    }

    public static function createOneUser($userInfo,$rolesId=[]){
        DB::beginTransaction();
        try{
            $user = AdminUser::create($userInfo);
            $user->detachRoles(null);
            if(!empty($rolesId)){
                $user->giveRoles($rolesId);
            }
        }catch (\Exception $e){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    public static function getOneUser($userId){
        return AdminUser::find($userId);
    }

    public static function updateRoles($userId,$rolesId){
        DB::beginTransaction();
        try{
            $user = AdminUser::find($userId);
            $user->detachRoles(null);
            if(!empty($rolesId)){
                $user->giveRoles($rolesId);
            }
        }catch (\Exception $e){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    public static function resetPasswd($userId){
        return AdminUser::find($userId)
                ->update(['password'=>bcrypt(self::INIT_PASSWD)]);
    }

    public static function modifyPasswd($userId,$passwd){
        return AdminUser::find($userId)
            ->update(['password'=>$passwd]);
    }



    public static function deleteOneUser($userId){
        return AdminUser::find($userId)
            ->delete();
    }



}